package com.tsn.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tsn.common.Result;
import com.tsn.entity.Comment;
import com.tsn.entity.Media;
import com.tsn.service.FileService;
import com.tsn.service.MediaService;
import com.tsn.util.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 图片视频 前端控制器
 * </p>
 *
 * @author tsn
 * @since 2021-08-13
 */
@RestController
@RequestMapping("/tsn/media")
public class MediaController {
    @Autowired
    FileService fileService;
    @Autowired
    MediaService mediaService;
    @PostMapping  (path = "/upload")
    public Result uploadFile(@RequestParam("file") MultipartFile multipartFiles) {

        return    fileService.fileUpload(multipartFiles);
    }
    @PostMapping  (path = "/uploadapp")
    public Result uploadFileToApp(MultipartFile[] multipartFiles) {

        return    fileService.upload(multipartFiles);
    }
    @GetMapping("/getVideos")
    public Result getVideoList(){
        QueryWrapper<Media> mediaQueryWrapper = new QueryWrapper<>();
        mediaQueryWrapper.eq("type",1);
        List<Media> list = mediaService.list(mediaQueryWrapper);
        return Result.success(list);
    }
    @PostMapping("/addVideo")
    public Result addVideo(@RequestBody JSONObject object){
        Media media = JSON.toJavaObject(object, Media.class);
        media.setType(1);
        mediaService.save(media);
        return Result.success(null);
    }
//    @ApiOperation("图片上传")
    @PostMapping("/uploadimg")
    public Result uploadFile(HttpServletRequest request) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = "/zjcentury/img/";

            MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;

            //对应前端的upload的name参数"file"
            MultipartFile file = req.getFile("file");
            // 上传并返回新文件名称
            FileUtils.fileUpload(file,file.getOriginalFilename(), filePath);
            Map<String, Object> result = new HashMap<>();
            result.put("fileName", file.getOriginalFilename());
            result.put("url", "/img/"+file.getOriginalFilename());
            return Result.success(result);
        }
        catch (Exception e)
        {
            return Result.failure(e.getMessage());
        }
    }


}

